﻿using System;
using Sripirom.ATS.Core.Domain;
using Sripirom.ATS.Core.UnitOfWork;
using Sripirom.ATS.Repository.NH.SessionStorage;
using NHibernate;
using Sripirom.ATS.Core.Logging;

namespace Sripirom.ATS.Repository.NH
{
    public class NHUnitOfWork : IUnitOfWork
    {
        public void RegisterAmended(IAggregateRoot entity,
                                    IUnitOfWorkRepository unitofWorkRepository)
        {
            SessionFactory.GetCurrentSession().SaveOrUpdate(entity);
        }

        public void RegisterNew(IAggregateRoot entity,
                                IUnitOfWorkRepository unitofWorkRepository)
        {
            SessionFactory.GetCurrentSession().Save(entity);
        }

        public void RegisterRemoved(IAggregateRoot entity,
                                    IUnitOfWorkRepository unitofWorkRepository)
        {
            SessionFactory.GetCurrentSession().Delete(entity);
        }

        public void Commit()
        {
            using (ITransaction transaction =
                           SessionFactory.GetCurrentSession().BeginTransaction())
            {
                try
                { transaction.Commit(); }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    LoggerFactory.CreateLog().LogError(ex.Message);
                    throw;
                }
            }
        }

        public void Rollback() {
            using (ITransaction transaction =
                           SessionFactory.GetCurrentSession().BeginTransaction())
            {
                try
                { 
                    transaction.Rollback();
                    LoggerFactory.CreateLog().LogInfo("Rollback");
                }
                catch (Exception ex)
                {
                    LoggerFactory.CreateLog().LogError(ex.Message, ex);
                    throw;
                }
            }
        }
                                                                 
        public void Evict(IAggregateRoot entity)
        {
            SessionFactory.GetCurrentSession().Evict(entity);
        }
    }

}
